//
//  CarouselView.m
//  WorkManager
//
//  Created by ukongm on 17/1/6.
//  Copyright © 2017年 ukongm. All rights reserved.
//

#import "CarouselView.h"

/** 控件tag起始值 */
static NSInteger const VIEW_TAG = 300;

@interface CarouselView()<UIScrollViewDelegate>

/** 滚动视图 */
@property(nonatomic,strong)UIScrollView* scrollView;
/** 页数指示 */
@property(nonatomic,strong)UIPageControl* pageCtrl;
/** 缓存已创建的视图 */
@property(nonatomic,strong)NSMutableDictionary* cacheDict;
/** 定时器 */
@property(nonatomic,strong)NSTimer* timer;

@end

@implementation CarouselView
{
    NSInteger _curIndex; //自动轮播的位置标记
    NSInteger _sourceCount; //数据的个数
}

- (NSMutableDictionary *)cacheDict{
    
    if (_cacheDict == nil) {
        _cacheDict = [NSMutableDictionary new];
    }
    return _cacheDict;
}

- (UIPageControl *)pageCtrl{
    
    if (_pageCtrl == nil) {
        
        CGFloat height = 20;
        _pageCtrl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, self.height - height, self.width, height)];
        
        _pageCtrl.userInteractionEnabled = NO;
        
        _pageCtrl.hidesForSinglePage = YES;
    }
    return _pageCtrl;
}

- (UIScrollView *)scrollView{
    
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        
        _scrollView.pagingEnabled = YES;
        
        _scrollView.showsHorizontalScrollIndicator = NO;
        
        _scrollView.delegate = self;
        
        _scrollView.bounces = NO;
    }
    return _scrollView;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    return  [self initWithFrame:frame style:CarouselViewShowStyleDefault];
}

- (instancetype)initWithFrame:(CGRect)frame style:(CarouselViewShowStyle)style{
    self = [super initWithFrame:frame];
    if (self) {
        _style = style;
        [self addSubview:self.scrollView];
        [self addSubview:self.pageCtrl];
        
        [self pageViewForStyle:style];
        
    }
    return self;
}

- (void)pageViewForStyle:(CarouselViewShowStyle)style{
    switch (style) {
        case CarouselViewShowStyleTitleRightIndicate:
        {
            CGSize size = [self.pageCtrl sizeForNumberOfPages:self.pageCtrl.numberOfPages];
            
            size.width += 10;
            
            self.pageCtrl.frame = CGRectMake(self.width - size.width, self.height - self.pageCtrl.height, size.width, self.pageCtrl.height);
            
            break;
        }
            
        default:
            break;
    }
}

- (void)setImageUrls:(NSArray<NSString *> *)imageUrls{
    
    _sourceCount = imageUrls.count;
    
    if (_sourceCount == 0) {
        return;
    }
    
    if (_sourceCount == 1) {
        
        _sourceCount = -1;
    }
    
    [self.scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    //排列第一个，和最后一个，   第一个是最后一张图。 最后一个是第一张图
    for (NSInteger i = 0;  i < _sourceCount+2; i++) {
        
        NSString* indexStr = [NSString stringWithFormat:@"%ld",i];
        
        NSString* imageUrl;
        
        if (i != 0 && i != _sourceCount + 1) {
            imageUrl = imageUrls[i - 1];
        }else if (i == 0 && _sourceCount != -1){
            imageUrl = imageUrls[_sourceCount - 1];
        }else if (i == _sourceCount + 1){
            imageUrl = imageUrls[0];
        }
        
        CGRect frame = CGRectMake(i * self.scrollView.width, 0, self.scrollView.width, self.scrollView.height);
        
        UIImageView* imageView = [self.cacheDict objectForKey:indexStr];
        
        if (!imageView) {
            imageView = [self createView];
            
            //根据风格去添加控件
            [self addViewWithStyle:self.style imageView:imageView andIndex:i];
            
            [self.cacheDict setObject:imageView forKey:indexStr];
        }
        
        imageView.tag = i + VIEW_TAG;
        
        imageView.frame = frame;
        
        [imageView sd_setImageWithURL:[NSURL URLWithString:imageUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            if (image == nil) {
                
                imageView.image = [UIImage imageNamed:imageUrl];
                
            }
            
        }];
//        imageView.image = [UIImage imageNamed:imageUrl];
        
        [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)]];
        
        imageView.userInteractionEnabled = YES;
        
        [self.scrollView addSubview:imageView];
    }
    
    NSInteger temp = _sourceCount == -1? 0 : 1;
    
    [self.scrollView setContentOffset:CGPointMake(self.scrollView.width * temp, 0)];
    self.scrollView.contentSize = CGSizeMake(self.scrollView.width * (_sourceCount + 2), 0);
    self.pageCtrl.numberOfPages = imageUrls.count;
    self.pageCtrl.currentPage = 0;
    
    [self pageViewForStyle:self.style];
}


- (UIImageView*)createView{
    UIImageView* imageView = [[UIImageView alloc] init];
    
//    imageView.backgroundColor = [UIColor arcColor];
    
    return imageView;
}

#pragma mark - 根据风格去添加控件
- (void)addViewWithStyle:(CarouselViewShowStyle)style imageView:(UIImageView*)imageView andIndex:(NSInteger)index{
    
    switch (style) {
        case CarouselViewShowStyleTitleRightIndicate:
        {
            NSString* name = nil;
            if (index != 0 && index != _sourceCount + 1) {
                name = self.titleNames[index - 1];
            }else if (index == 0){
                name = self.titleNames[_sourceCount - 1];
            }else if (index == _sourceCount + 1){
                name = self.titleNames[0];
            }
            CGFloat height = 20;
            UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0, imageView.height - height, imageView.width, height)];
            label.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
            label.text = [@"  " stringByAppendingString:name];
            label.backgroundColor = [UIColor blackColor];
            label.textColor = [UIColor whiteColor];
            label.font = [UIFont systemFontOfSize:13];
            label.alpha = 0.8;
            [imageView addSubview:label];
            break;
        }
        default:
            break;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    _curIndex = (scrollView.contentOffset.x) / scrollView.width;
    
    if (_curIndex == 0 && scrollView.contentOffset.x == 0) {
        
        _curIndex = _sourceCount;
        
        [scrollView setContentOffset:CGPointMake(_curIndex * scrollView.width, 0) animated:NO];
    }else if(_curIndex == _sourceCount+1){
        
        _curIndex = 1;
        [scrollView setContentOffset:CGPointMake((_curIndex) * scrollView.width, 0) animated:NO];
    }
    
    self.pageCtrl.currentPage = _curIndex - 1;
    
}

- (void)tapAction:(UITapGestureRecognizer*)tap{
    NSInteger index = tap.view.tag - VIEW_TAG;
    
    if (index == _sourceCount + 1) {
        index = 1;
    }else if(index == 0){
        index = _sourceCount;
    }
    
    //优先调用block
    if (self.actionComplate) {
        self.actionComplate(index);
    }else{
        if (self.delegate && [self.delegate respondsToSelector:@selector(actionAtIndex:)]) {
            [self.delegate actionAtIndex:index];
        }
    }
}

#pragma mark - 轮播
- (void)setAutoCarousel:(BOOL)isAuto andTime:(NSInteger)time{
    
    if (isAuto) {
        [self startTimerForTime:time];
    }else{
        [self stopTimer];
    }
    
}

- (void)startTimerForTime:(NSInteger)time{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(autoPlayView) userInfo:nil repeats:YES];
}

- (void)stopTimer{
    if (self.timer != nil) {
        [self.timer invalidate];
    }
}

- (void)autoPlayView{
    
    if (_sourceCount == -1) {
        [self stopTimer];
        return;
    }
    
    BOOL animated = YES;
    
    if (_curIndex == _sourceCount + 1) {
        animated = NO;
    }
    
    [self.scrollView setContentOffset:CGPointMake(self.scrollView.width * (_curIndex + 1), 0) animated:animated];
}


@end
